// 检验服务器有效模块
//引入sha1模块
const sha1 = require('sha1');
//引入config模块
const config = require('../connfig');
//引入tool模块
const { getUserDataAsync, parseXMLAsyns, formatMessage } = require('../utlis/tool');
//引入template模块
const template = require('./template');
//引入reply模块
const reply = require('./reply');
module.exports = () => {
    return async(req, res, next) => {
        const { signature, echostr, timestamp, nonce } = req.query;
        const { Token } = config;
        const sha1Str = sha1([timestamp, nonce, Token].sort().join(''))
        if (req.method === 'GET') {
            if (sha1Str == signature) {
                res.send(echostr);
            } else {
                res.end('error')
            }
        } else if (req.method === 'POST') {
            if (sha1Str !== signature) {
                res.end('error')
            }
            console.log(req.query);
            const xmlDtat = await getUserDataAsync(req);
            console.log(xmlDtat);


            const jsData = await parseXMLAsyns(xmlDtat)
            console.log(jsData);


            const message = formatMessage(jsData);
            console.log(message);


            const options = reply(message)

            // 最终回复用户的信息
            let replyMessage = template(options)
            console.log(replyMessage);


            // 返回响应给微信服务器
            res.send(replyMessage);
        } else {
            res.end('error服务器错误')
        }
    }


}